/**
 * @author molnala
 */

 function loadScript(fileUrl, checker, initializator) {
     // check whether the script(s) is/are not loaded already
     var loaded = checker();
     
     if (!loaded) {
        // find the head element
        var head = document.getElementsByTagName('head')[0];
                
        // create new script element for each file and append it to the head
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = fileUrl;
        script.onload = initializator;
        script.onreadystatechange = function(){
            if (this.readyState == 'complete') {
                initializator();
            }
        };
        head.appendChild(script);    
    }
    else {
        initializator();
    }
 }
 
 function loadScripts(fileUrls, checkers, initializator, index, postFunc) {  
    if (index == undefined) {
        index = 0;
    }
    
    if (index >= fileUrls.length) {
        return -1;
    }
    
    if (fileUrls.length != checkers.length) {
        return -1;
    }
    
    var loaded = checkers[index]();
    
    if (!loaded) {
        var head = document.getElementsByTagName('head')[0];
        
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = fileUrls[index];
        script.onload = (index == fileUrls.length - 1 
            ? function(){ initializator(); if (postFunc!=undefined) postFunc();} 
            : function(){ loadScripts(fileUrls, checkers, initializator, index + 1, postFunc);});
        script.onreadystatechange = (index == fileUrls.length - 1 ? function(){
            if (this.readyState == 'complete' || this.readyState == 'loaded') {
                initializator();
                if (postFunc != undefined) 
                    postFunc();
            }
        }
        : function(){
            if (this.readyState == 'complete' || this.readyState == 'loaded') {
                loadScripts(fileUrls, checkers, initializator, index + 1, postFunc);
            }
        });
        head.appendChild(script);
    }
    else {
        if (index == fileUrls.length - 1 && postFunc!=undefined) {
            postFunc();
        }
        else {
            loadScripts(fileUrls, checkers, initializator, index + 1, postFunc);
        }
    }
 }
